<template>
  <div class="box">
    <!-- <van-form @submit="onSubmit"> -->
    <van-form @submit="submitHandler">
      <h1>登录</h1>
      <van-field
        v-model="username"
        name="name"
        label="用户名"
        placeholder="sun"
        :rules="[{ required: true,pattern, message: '用户名只能是数字或字母，且长度为3~8' }]"
      />
      <van-field
        v-model="password"
        name="password"
        label="密码"
        placeholder="123456"
        :rules="[{ required: true,pattern, message: '用户名只能是数字或字母，且长度为3~8' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
      pattern: /^[A-Za-z0-9]{3,8}$/,
    };
  },
  methods: {
    // onSubmit(values) {
    //   if ((values.name == "sun" && values.password == 123456)) {
    //     console.log(values.name, values.password);
    //      this.$router.push("/home");
    //   }
    async submitHandler(e) {
      e.preventDefault();
      try {
        const result = await this.$http.get("/login", {
          params: this.model,
        });
        if (result.code == "0") {
          this.$store.commit("settoken", result.token);
          window.localStorage.setItem("token", result.token);

          //判断路由是否带参，带参就去到重定向参数地址，否则就去首页
          if (this.$route.query.redirect) {
            this.$router.replace({ path: this.$route.query.redirect });
          } else {
            this.$router.replace({ path: "/home" });
          }
        } else {
          alert(result.message);
        }
      } 
      catch (err) {
        console.log(err);
      }
    }}
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.box {
  width: 100vw;
  height: 100vh;
  background: url(../assets/bg.jpg) no-repeat;
  background-size: 100% 120%;
  position: relative;
}
h1 {
  color: #fff;
  text-align: center;
  margin: 3vh 0px;
}
form {
  width: 70vw;
  margin-left: 15vw;
  margin-top: 25vh;
  position: absolute;
}
</style>